const {
  getAppUser,
  getProjects,
  getBuildUserByProject,
  getImpls,
  getImplUserByProject,
  getConsumptionList,
  addDispatch,
  dictType,
  getTransList,
  getCarList,
  upload,
} = require('../../utils/api');
const { formatDate, validateFields } = require('../../utils/tool');
let projectList = []; // 项目列表
let implList = []; // 施工单位列表
let managerUserList = []; // 消纳场列表
let garbageTypeList = []; // 垃圾类型列表
let projectTypeList = []; // 工程类型列表
let transIdList = []; // 外运输单位列表
let selfCarList = []; // 本单位车辆列表
let carIdList = []; // 车辆列表
let transId = '';
let company = '';
let buildId = '';

const rules = {
  projectName: '请选择项目名称',
  company: '请选择施工单位',
  person: '请输入联系人姓名',
  phone: '请输入联系人手机号',
  address: '请输入项目地址',
  buildName: '请输入建设单位名称',
  buildAddress: '请输入建设单位地址',
  buildLegalPerson: '请输入建设单位法人',
  buildLegalPhone: '请输入建设单位法人手机号',
  buildResponsible: '请输入项目负责单位',
  buildResponsiblePhone: '请输入项目负责单位手机号',
  implName: '请输入施工单位名称',
  implLegalPerson: '请输入施工单位法人',
  implLegalPhone: '请输入施工单位法人手机号',
  implResponsible: '请输入项目负责单位',
  implResponsiblePhone: '请输入项目负责单位手机号',
  managerUserId: '请选择消纳场',
  garbageType: '请选择垃圾类型',
  projectType: '请选择工程类型',
  startTime: '请选择工程开始时间',
  endTime: '请选择工程结束时间',
  imgs: '请上传路线证明',
  selfCarList: '请选择本单位车辆',
  transIdList: '请选择外运输单位',
  carIdList: '请选择车辆',
  cnsx: '请阅读保洁责任承诺事项',
};

const MAXDATE = new Date('2050-12-31 11:59:59').getTime();

Page({
  data: {
    loading: false,
    checkboxResult: [],
    checkboxColumns: [],
    checkboxLabel: '',
    checkboxValue: '',
    columns: [],
    columnsKey: '',
    showPopup: false,
    currentPicker: '',
    showTimePopup: false,
    showCheckboxPopup: false,
    currentTimePicker: '',
    minDate: new Date().getTime(),
    maxDate: MAXDATE,
    currentDate: new Date().getTime(),
    managerUserName: '', // 消纳场名称
    garbageTypeName: '', // 垃圾类型名称
    projectTypeName: '', // 工程类型名称
    selfCarNames: '', // 本单位车辆名称
    transIdNames: '', // 外运输单位名称
    carIdNames: '', // 车辆名称
    form: {
      projectName: '', // 项目名称
      company: '', // 施工单位
      person: '', // 联系人姓名
      phone: '', // 联系人手机
      address: '', // 项目地址
      addrGis: '', // 项目地址经纬度
      buildName: '', // 建设单位名称
      buildAddress: '', // 建设单位地址
      buildLegalPerson: '', // 建设单位法定代表人
      buildLegalPhone: '', // 建设单位法定代表人手机
      buildResponsible: '', // 建设单位负责人
      buildResponsiblePhone: '', // 建设单位负责人手机
      implName: '', // 施工单位名称
      implLegalPerson: '', // 施工单位法定代表人
      implLegalPhone: '', // 施工单位法定代表人手机
      implResponsible: '', // 施工单位负责人
      implResponsiblePhone: '', // 施工单位负责人手机
      managerUserId: '', // 消纳场
      garbageType: '', // 垃圾类型
      projectType: '', // 工程类型
      startTime: '', // 运输起始时间
      endTime: '', // 运输结束时间
      pathName: '', // 运输路线
      imgs: [], // 路线证明
      selfCarList: [], // 本单位车辆
      transIdList: [], // 外运输单位
      carIdList: [], // 车辆
      cnsx: false,
    },
  },

  onLoad(opts) {
    getAppUser().then((res) => {
      transId = res?.data?.id;
      company = res?.data?.company;
      this.setData({
        ['form.person']: res?.data?.responsible,
        ['form.phone']: res?.data?.responsiblePhone,
      });
      getProjects({ transId: company }).then((res) => {
        projectList = res.data;
      });
      getImpls({ transId: company }).then((res) => {
        implList = res.data;
      });
    });
    getConsumptionList().then((res) => {
      managerUserList = res.data;
    });
    dictType('bus_project_location').then((res) => {
      garbageTypeList = res.data;
    });
    dictType('bus_engin_type').then((res) => {
      projectTypeList = res.data;
    });
    getTransList().then((res) => {
      transIdList = res.data;
    });
  },

  handlePickerTap(e) {
    const { type } = e.currentTarget?.dataset || {};
    if (type === 'company' && !this.data.form.projectName) {
      wx.showToast({ title: '请选择项目名称', icon: 'none' });
      return;
    }
    let columns = [];
    let columnsKey = '';
    switch (type) {
      case 'projectName':
        columns = projectList;
        columnsKey = '';
        break;
      case 'company':
        columns = implList;
        columnsKey = '';
        break;
      case 'managerUserId':
        columns = managerUserList;
        columnsKey = 'names';
        break;
      case 'garbageType':
        columns = garbageTypeList;
        columnsKey = 'dictLabel';
        break;
      case 'projectType':
        columns = projectTypeList;
        columnsKey = 'dictLabel';
        break;
    }

    this.setData({
      currentPicker: type,
      columns,
      columnsKey,
      showPopup: true,
    });
  },

  handlePickerCheckboxTap(e) {
    const { type } = e.currentTarget?.dataset || {};
    let checkboxColumns = [];
    let checkboxLabel = '';
    let checkboxValue = '';
    switch (type) {
      case 'selfCarList':
        checkboxColumns = selfCarList;
        checkboxLabel = 'licensePlate';
        checkboxValue = 'id';
        break;

      case 'transIdList':
        checkboxColumns = transIdList;
        checkboxLabel = 'company';
        checkboxValue = 'id';
        break;

      case 'carIdList':
        checkboxColumns = carIdList;
        checkboxLabel = 'licensePlate';
        checkboxValue = 'id';
        break;
    }

    this.setData({
      currentPicker: type,
      checkboxColumns,
      checkboxLabel,
      checkboxValue,
      showCheckboxPopup: true,
    });

    setTimeout(() => {
      this.setData({
        checkboxResult: this.data.form[type],
      });
    }, 100);
  },

  onCheckboxChange(e) {
    this.setData({
      checkboxResult: e.detail,
    });
  },

  onCheckboxConfirm() {
    const { currentPicker, checkboxResult } = this.data;
    switch (currentPicker) {
      case 'selfCarList':
        this.setData({
          ['form.selfCarList']: checkboxResult,
          selfCarNames: checkboxResult.map((item) => {
            return selfCarList.find((trans) => trans.id == item).licensePlate;
          }),
          showCheckboxPopup: false,
        });
        break;

      case 'transIdList':
        this.setData({
          ['form.transIdList']: checkboxResult,
          transIdNames: checkboxResult.map((item) => {
            return transIdList.find((trans) => trans.id == item).company;
          }),
          showCheckboxPopup: false,
        });
        this.getCarListByTrans({ companyIds: checkboxResult });
        break;

      case 'carIdList':
        this.setData({
          ['form.carIdList']: checkboxResult,
          carIdNames: checkboxResult.map((item) => {
            return carIdList.find((trans) => trans.id == item).licensePlate;
          }),
          showCheckboxPopup: false,
        });
        break;
    }
  },

  getCarListByTrans({ startTime, companyIds }) {
    if (startTime) {
      getCarList({ startTime, companyIds: transId }).then((res) => {
        selfCarList = res.data;
      });
      getCarList({ startTime }).then((res) => {
        carIdList = res.data;
      });
    } else {
      const stime = this.data.form.startTime;
      getCarList({ startTime: stime, companyIds: companyIds?.join?.(',') }).then((res) => {
        carIdList = res.data;
      });
    }
  },

  onConfirm(e) {
    const { value } = e.detail;
    const currentPicker = this.data.currentPicker;

    switch (currentPicker) {
      case 'projectName':
        this.setData({
          ['form.projectName']: value,
          showPopup: false,
        });
        this.getBuildUserByProject(value);
        break;
      case 'company':
        this.setData({
          ['form.company']: value,
          showPopup: false,
        });
        this.getImplUserByProject(value);
        break;
      case 'managerUserId':
        this.setData({
          ['form.managerUserId']: value.id,
          managerUserName: value.names,
          showPopup: false,
        });
        break;
      case 'garbageType':
        this.setData({
          ['form.garbageType']: value.dictValue,
          garbageTypeName: value.dictLabel,
          showPopup: false,
        });
        break;
      case 'projectType':
        this.setData({
          ['form.projectType']: value.dictValue,
          projectTypeName: value.dictLabel,
          showPopup: false,
        });
        break;
    }
  },

  onCancel() {
    this.setData({
      showPopup: false,
      showTimePopup: false,
      showCheckboxPopup: false,
    });
  },

  onTimeConfirm(e) {
    const time = e.detail;
    const { currentTimePicker } = this.data;
    const formatTime = formatDate(time);
    let dataKey = '';
    switch (currentTimePicker) {
      case 'startTime':
        dataKey = 'form.startTime';
        this.getCarListByTrans({ startTime: formatTime });
        break;
      case 'endTime':
        dataKey = 'form.endTime';
        break;
    }
    this.setData({
      [dataKey]: formatTime,
      showTimePopup: false,
    });
  },

  handlePickerTimeTap(e) {
    const type = e.currentTarget.dataset.type;
    if (type === 'startTime') {
      if (this.data.form.endTime) {
        this.setData({
          minDate: new Date().getTime(),
          maxDate: new Date(this.data.form.endTime).getTime(),
        });
      }
    }
    if (type === 'endTime') {
      if (this.data.form.startTime) {
        this.setData({
          minDate: new Date(this.data.form.startTime).getTime(),
          maxDate: MAXDATE,
        });
      }
    }
    this.setData({
      showTimePopup: true,
      currentTimePicker: type,
    });
  },

  getBuildUserByProject(project) {
    getBuildUserByProject({ transId: company, project }).then((res) => {
      if (!res?.data) {
        wx.showToast({ title: '未查到项目关联的建设单位信息', icon: 'none' });
        return;
      }
      buildId = res.data?.id;
      this.setData({
        ['form.address']: res.data?.appBuildInfo?.projectAddress,
        ['form.addrGis']: res.data?.appBuildInfo?.projectGis,
        ['form.buildName']: res.data.company,
        ['form.buildAddress']: res.data.address,
        ['form.buildLegalPerson']: res.data.legalPerson,
        ['form.buildLegalPhone']: res.data.legalPhone,
        ['form.buildResponsible']: res.data?.appBuildInfo?.projectPerson,
        ['form.buildResponsiblePhone']: res.data?.appBuildInfo?.projectPhone,
      });
    });
  },

  getImplUserByProject(implName) {
    const project = this.data.form.projectName;
    getImplUserByProject({ transId: company, project, implName }).then((res) => {
      if (!res?.data) {
        wx.showToast({ title: '未查到施工单位信息', icon: 'none' });
        return;
      }
      this.setData({
        ['form.implName']: res.data.company,
        ['form.implLegalPerson']: res.data.legalPerson,
        ['form.implLegalPhone']: res.data.legalPhone,
        ['form.implResponsible']: res.data?.responsible,
        ['form.implResponsiblePhone']: res.data?.responsiblePhone,
      });
    });
  },

  handleFieldInput(e) {
    const { type } = e.currentTarget.dataset;
    this.setData({
      [`form.${type}`]: e.detail,
    });
  },

  handleViewAddress() {
    wx.authorize({
      scope: 'scope.userLocation',
      success: async () => {
        const { addrGis } = this.data.form || {};
        if (addrGis) {
          let longitude = '';
          let latitude = '';
          const g = addrGis.split(',');
          longitude = g?.[0];
          latitude = g?.[1];
          wx.openLocation({
            longitude: Number(longitude || ''),
            latitude: Number(latitude || ''),
            complete: (res) => {
              console.log(res);
            },
          });
        }
      },
    });
  },

  handleAfterRead(e) {
    const { file } = e.detail;
    const { imgs } = this.data.form;
    upload(file.url).then((res) => {
      this.setData({
        ['form.imgs']: [...imgs, { url: res.url }],
      });
    });
  },

  handleDelete(e) {
    const { index } = e.detail;
    const { imgs } = this.data.form;
    this.setData({
      ['form.imgs']: imgs.filter((_, i) => i !== index),
    });
  },

  handleCnsxCheck() {
    this.setData({
      ['form.cnsx']: !this.data.form.cnsx,
    });
  },

  handleSubmit() {
    const { form } = this.data;
    if (!validateFields(form, rules)) {
      return;
    }
    const newForm = JSON.parse(JSON.stringify(form));
    newForm.appUserId = transId;
    newForm.buildId = buildId;
    newForm.transList = newForm?.transIdList.toString();
    newForm.imgs = newForm?.imgs?.map?.((item) => item.url)?.join?.(',');
    newForm.type = 1;
    this.setData({ loading: true });
    addDispatch(newForm)
      .then((res) => {
        this.setData({ loading: false });
        wx.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 2000,
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 2000);
      })
      .catch(() => {
        this.setData({ loading: false });
        wx.showToast({ title: '提交失败', icon: 'error' });
      });
  },
});
